import React, { useState, useEffect, useCallback } from 'react';
import SerialPortLayout from './SerialPortLayout';
import {
  Box,

  Typography,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  List,
  ListItem,
  Alert,

  CircularProgress,
  Divider,
  IconButton
} from '@mui/material';
import RefreshIcon from '@mui/icons-material/Refresh';
import SendIcon from '@mui/icons-material/Send';
import ClearIcon from '@mui/icons-material/Clear';

// 导入串口设备接口和API响应接口
// 重新定义接口，避免导入路径问题
export interface SerialPortDevice {
  path: string;
  manufacturer: string;
  serialNumber: string;
  pnpId: string;
  locationId: string;
  productId: string;
  vendorId: string;
}

export interface ApiResponse {
  success: boolean;
  message?: string;
  error?: string;
}

// 定义串口数据接口
interface SerialData {
  timestamp: Date;
  data: string;
  type: 'recv' | 'send';
}

const SerialPortComponent: React.FC = () => {
  // 状态管理
  const [ports, setPorts] = useState<SerialPortDevice[]>([]);
  const [selectedPort, setSelectedPort] = useState<string>('');
  const [baudRate, setBaudRate] = useState<number>(9600);
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [dataList, setDataList] = useState<SerialData[]>([]);
  const [message, setMessage] = useState<string>('');
  const [appendNewline, setAppendNewline] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [snackbarOpen, setSnackbarOpen] = useState<boolean>(false);
  const [snackbarMessage, setSnackbarMessage] = useState<string>('');

  // 波特率选项
  const baudRates = [9600, 19200, 38400, 57600, 115200, 230400];

  // 获取可用串口列表
  const getSerialPorts = useCallback(async () => {
    setLoading(true);
    try {
      console.log('📊 检查window对象:', Object.keys(window).includes('electronAPI'));
      console.log('🔍 window对象属性:', Object.keys(window).join(', '));
      console.log('🔧 electronAPI类型:', typeof window.electronAPI);
      
      if (!window.electronAPI) {
        throw new Error('Electron API 不可用 - 请检查preload脚本');
      }

      // 尝试调用hello方法测试基本连接
      console.log('🔄 尝试调用hello方法...');
      const helloResult = window.electronAPI.hello();
      console.log('✅ hello结果:', helloResult);
      
      // 获取真实串口列表
      console.log('🔄 获取可用串口列表...');
      const portsList = await window.electronAPI.listSerialPorts();
      console.log('✅ 获取到的串口列表:', portsList);
      
      setPorts(portsList);
      
      if (portsList.length === 0) {
        showSnackbar('未检测到可用串口');
      } else {
        showSnackbar(`检测到 ${portsList.length} 个可用串口`);
      }
      
      setError(null);
      
    } catch (err) {
      const errorMsg = `获取串口列表失败: ${err instanceof Error ? err.message : String(err)}`;
      setError(errorMsg);
      console.error('❌ API调用错误:', err);
      setPorts([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // 打开串口
  const openPort = async () => {
    console.log('🔌 打开串口');
    if (!selectedPort) {
      setError('请先选择一个串口');
      return;
    }

    if (!window.electronAPI) {
      setError('Electron API 不可用');
      return;
    }

    try {
      setLoading(true);
      console.log(`尝试打开串口: ${selectedPort}, 波特率: ${baudRate}`);
      const result: ApiResponse = await window.electronAPI.openSerialPort(selectedPort, baudRate);
      
      if (result.success) {
        setIsConnected(true);
        showSnackbar(`已连接到 ${selectedPort}`);
        
        // 设置串口数据接收回调
        window.electronAPI.onSerialData((data: string) => {
          console.log('📨 收到串口数据:', data);
          setDataList(prev => [...prev, {
            timestamp: new Date(),
            data,
            type: 'recv' as const
          }].slice(-100)); // 保留最近100条数据
        });
        
        setError(null);
      } else {
        setError(result.error || '打开串口失败');
      }
    } catch (err) {
      const errorMsg = `打开串口失败: ${err instanceof Error ? err.message : String(err)}`;
      setError(errorMsg);
      console.error('打开串口错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 关闭串口
  const closePort = async () => {
    if (!window.electronAPI) {
      setError('Electron API 不可用');
      setIsConnected(false);
      return;
    }

    try {
      setLoading(true);
      console.log('🔌 关闭串口');
      const result: ApiResponse = await window.electronAPI.closeSerialPort();
      
      if (result.success) {
        setIsConnected(false);
        showSnackbar('串口已关闭');
        
        // 清除数据回调
        if (window.serialDataCallback) {
          window.serialDataCallback = undefined;
        }
      } else {
        setError(result.error || '关闭串口失败');
      }
    } catch (err) {
      const errorMsg = `关闭串口失败: ${err instanceof Error ? err.message : String(err)}`;
      setError(errorMsg);
      console.error('关闭串口错误:', err);
      setIsConnected(false);
    } finally {
      setLoading(false);
    }
  };

  // 发送数据
  const sendData = async () => {
    if (!message.trim()) {
      return;
    }

    if (!window.electronAPI) {
      setError('Electron API 不可用');
      return;
    }

    let sendMsg = message;
    if (appendNewline) {
      sendMsg += '\r\n';
    }

    try {
      console.log(`发送数据: ${sendMsg}`);
      const result: ApiResponse = await window.electronAPI.sendData(sendMsg);
      
      if (result.success) {
        // 将发送的数据添加到列表中
        setDataList(prev => [...prev, {
          timestamp: new Date(),
          data: sendMsg,
          type: 'send' as const
        }].slice(-100));
        showSnackbar('数据发送成功');
        // 保留输入框内容，不清除
      } else {
        setError(result.error || '发送数据失败');
      }
    } catch (err) {
      const errorMsg = `发送数据失败: ${err instanceof Error ? err.message : String(err)}`;
      setError(errorMsg);
      console.error('发送数据错误:', err);
    }
  };

  // 清空接收数据
  const clearData = () => {
    setDataList([]);
  };

  // 显示提示信息
  const showSnackbar = (msg: string) => {
    setSnackbarMessage(msg);
    setSnackbarOpen(true);
  };

  // 组件挂载时获取串口列表
  useEffect(() => {
    getSerialPorts();
  }, [getSerialPorts]);

  // 组件卸载时的清理
  useEffect(() => {
    return () => {
      if (isConnected && window.electronAPI) {
        console.log('组件卸载，关闭串口连接');
        window.electronAPI.closeSerialPort().catch(err => {
          console.error('关闭串口失败:', err);
        });
      }
      // 清除数据回调
      if (window.serialDataCallback) {
        window.serialDataCallback = undefined;
      }
    };
  }, [isConnected]);

  // 渲染时直接检查window对象
  console.log('🎯 组件渲染 - 检查window.electronAPI:', window.electronAPI);

  // 处理snackbar关闭
  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
  };

  return (
    <SerialPortLayout
      snackbarOpen={snackbarOpen}
      snackbarMessage={snackbarMessage}
      onSnackbarClose={handleSnackbarClose}
      left={
        <>
          <Typography variant="subtitle2" color="textSecondary" fontWeight="bold">
            串口配置
          </Typography>
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel id="port-select-label">选择串口</InputLabel>
            <Select
              labelId="port-select-label"
              value={selectedPort}
              label="选择串口"
              onChange={(e) => setSelectedPort(e.target.value)}
              disabled={loading || isConnected}
            >
              {ports.map(port => (
                <MenuItem key={port.path} value={port.path}>
                  {port.path} - {port.manufacturer}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            fullWidth
            sx={{ mt: 2 }}
            onClick={getSerialPorts}
            disabled={loading}
          >
            {loading ? <CircularProgress size={20} /> : '刷新串口'}
          </Button>
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel id="baudrate-select-label">波特率</InputLabel>
            <Select
              labelId="baudrate-select-label"
              value={baudRate}
              label="波特率"
              onChange={(e) => setBaudRate(e.target.value as number)}
              disabled={isConnected}
            >
              {baudRates.map(rate => (
                <MenuItem key={rate} value={rate}>
                  {rate}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <Button
            variant="contained"
            color="primary"
            fullWidth
            sx={{ mt: 2 }}
            onClick={openPort}
            disabled={!selectedPort || isConnected}
          >
            连接
          </Button>
          <Button
            variant="contained"
            color="error"
            fullWidth
            sx={{ mt: 2 }}
            onClick={closePort}
            disabled={!isConnected}
          >
            断开
          </Button>
          <Box sx={{ mt: 2 }}>
            <Typography variant="body2" color={isConnected ? "success.main" : "error.main"} fontWeight="medium">
              连接状态: {isConnected ? `已连接到 ${selectedPort}` : '未连接'}
            </Typography>
          </Box>
          {/* 调试信息显示 */}
          <Box sx={{ mt: 2, p: 1, bgcolor: '#fff', borderRadius: 1 }}>
            <Typography variant="subtitle2" color="textSecondary">
              调试信息:
            </Typography>
            <Typography variant="body2" sx={{ mt: 1 }}>
              Electron API 存在: {!!window.electronAPI ? '✅ 是' : '❌ 否'}
            </Typography>
            <Typography variant="body2">
              API 类型: {typeof window.electronAPI}
            </Typography>
          </Box>
          {error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {error}
            </Alert>
          )}
        </>
      }
      right={
        <>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 2 }}>
              <Box sx={{ display: { xs: 'flex', sm: 'flex' }, flexDirection: { xs: 'column', sm: 'row' }, gap: 2 }}>
                <Box sx={{ flex: 1 }}>
                  <TextField
                    fullWidth
                    label="发送数据"
                    variant="outlined"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    disabled={!isConnected}
                    onKeyPress={(e) => e.key === 'Enter' && sendData()}
                  />
                </Box>
                <Box sx={{ display: 'flex', flexDirection: 'column', minWidth: { sm: '150px' } }}>
                  <Button
                    variant="contained"
                    startIcon={<SendIcon />}
                    fullWidth
                    onClick={sendData}
                    disabled={!isConnected || !message.trim()}
                  >
                    发送
                  </Button>
                  <FormControl sx={{ mt: 1, display: 'flex', alignItems: 'center' }}>
                    <label style={{ fontSize: 13, display: 'flex', alignItems: 'center' }}>
                      <input
                        type="checkbox"
                        checked={appendNewline}
                        onChange={e => setAppendNewline(e.target.checked)}
                        disabled={!isConnected}
                        style={{ marginRight: 4 }}
                      />
                      发送时自动加回车换行
                    </label>
                  </FormControl>
                </Box>
              </Box>
            </Box>
          <Divider sx={{ my: 1 }} />
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
              <Typography variant="h6" fontWeight="medium">收发消息</Typography>
              <IconButton size="small" onClick={clearData} color="primary">
                <ClearIcon />
              </IconButton>
            </Box>
          <Box
            sx={{
              flex: 1,
              minHeight: 300,
              maxHeight: 450,
              overflowY: 'auto',
              border: '1px solid #e0e0e0',
              borderRadius: 1,
              p: 2,
              backgroundColor: '#fff'
            }}
          >
            {dataList.length === 0 ? (
              <Typography variant="body2" color="text.secondary" align="center" sx={{ py: 2 }}>
                暂无数据
              </Typography>
            ) : (
              <List dense sx={{ width: '100%' }}>
                {dataList.map((item, index) => (
                  <ListItem 
                    key={index} 
                    sx={{
                      justifyContent: item.type === 'send' ? 'flex-end' : 'flex-start',
                      mb: 1
                    }}
                  >
                    <Box 
                      sx={{
                        maxWidth: '100%',
                        p: 1.5,
                        borderRadius: 2,
                        bgcolor: item.type === 'send' ? '#e3f2fd' : '#f1f8e9',
                        borderLeft: item.type === 'send' ? 'none' : '4px solid #4caf50',
                        borderRight: item.type === 'send' ? '4px solid #1976d2' : 'none'
                      }}
                    >
                      <Typography 
                        variant="body2" 
                        sx={{
                          wordBreak: 'break-word',
                          color: item.type === 'send' ? '#0d47a1' : '#246927ff',
                          fontWeight: item.type === 'send' ? 500 : 400
                        }}
                      >
                        {item.data}
                      </Typography>
                      <Typography 
                        variant="caption" 
                        color="text.secondary" 
                        sx={{ display: 'block', mt: 0.5 }}
                      >
                        {item.type === 'send' ? '发送' : '接收'}: {item.timestamp.toLocaleTimeString()}
                      </Typography>
                    </Box>
                  </ListItem>
                ))}
              </List>
            )}
          </Box>
        </>
      }
    />
  );
};

export default SerialPortComponent;